<?php

class LoginController extends Zend_Controller_Action {

    protected $_auth;

    public function init() {

        $this->_auth = Zend_Auth::getInstance();
        $this->_helper->layout->setLayout('layout-simple');
    }

    public function indexAction() {

        // Formulaire d'authentification
        $form = new Application_Form_Login();
        $this->view->message = null;

        if ($this->getRequest()->isPost()) {
            if (!$form->isValid($_POST)) {

                $this->view->form = $form;
                return;
            } else {
                $data = $form->getValues();

                // var_dump($data);

                $authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table::getDefaultAdapter());
                $authAdapter->setTableName('userCabinet')
                        ->setCredentialColumn('password')
                        ->setIdentityColumn('login');
                // ->setCredentialTreatment('MD5(?)');

                $authAdapter->setIdentity($data['login']);
                $authAdapter->setCredential($data['password']);

                $auth = $this->_auth; // Zend_Auth::getInstance();
                $result = $auth->authenticate($authAdapter);
                if ($result->isValid()) {

                    // to help thwart session fixation/hijacking
                    if ($form->getValue('rememberMe') == 1) {
                        // remember the session for 604800s = 7 days
                        Zend_Session::rememberMe(604800);
                    } else {
                        // do not remember the session
                        Zend_Session::forgetMe();
                    }

                    $userInfo = $authAdapter->getResultRowObject(null, array('password'));

                    $authStorage = $auth->getStorage();
                    $authStorage->write($userInfo);
                    $this->_redirect('');
                } else {
                    $this->view->message = "Echec de l'identification";
                }
            }
        }
        $this->view->form = $form;
    }

    public function logoutAction() {

        if ($this->_auth) {
            $auth = $this->_auth; // Zend_Auth::getInstance();
            $auth->clearIdentity();
            //Zend_session::destroy();
            Zend_Session::destroy(true);
        }
        $this->_redirect('login');
    }

}

